package service

import (
	"encoding/json"
	"github.com/gin-gonic/gin"
	uuid "github.com/satori/go.uuid"
	"guns-go/global"
	"guns-go/model"
	"guns-go/model/request"
)

func IsSuperAdmin(c *gin.Context) (error, bool) {

	err, user := GetUser(c)

	if err != nil {
		return err, false
	}

	if user.AdminType == global.SuperAdmin {
		return err, true
	} else {
		return err, false
	}
}

func GetUser(c *gin.Context) (err error, u *model.SysUser) {

	gUuid := GetUuid(c)

	//从redis 获取用户信息
	err, userStr := GetRedisJWT(gUuid)

	if err != nil || userStr == "" {
		return err, nil
	}

	user := model.SysUser{}
	err = json.Unmarshal([]byte(userStr), &user)

	return err, &user
}

// 从Gin的Context中获取从jwt解析出来的UUID
func GetUuid(c *gin.Context) uuid.UUID {
	if claims, exists := c.Get("claims"); !exists {
		global.GVA_LOG.Error("从Gin的Context中获取从jwt解析出来的UUID失败, 请检查路由是否使用jwt中间件")
		return uuid.UUID{}
	} else {
		waitUse := claims.(*request.CustomClaims)
		return waitUse.Uuid
	}
}

// 从Gin的Context中获取从jwt解析出来的UserRoleIds
func GetUserRoleIds(c *gin.Context) []int {
	if claims, exists := c.Get("claims"); !exists {
		global.GVA_LOG.Error("从Gin的Context中获取从jwt解析出来的UserRoleIds失败, 请检查路由是否使用jwt中间件")
		return nil
	} else {
		waitUse := claims.(*request.CustomClaims)
		return waitUse.UserRoleIds
	}
}
